using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using JGSY.CMS.LowCode.Platform.Application.DTOs;
using JGSY.CMS.LowCode.Platform.Application.Interfaces;

namespace JGSY.CMS.LowCode.Platform.Controllers
{
    /// <summary>
    /// 团队成员管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class TeamMembersController : ControllerBase
    {
        private readonly ITeamMemberAppService _teamMemberService;
        private readonly ILogger<TeamMembersController> _logger;

        public TeamMembersController(
            ITeamMemberAppService teamMemberService,
            ILogger<TeamMembersController> logger)
        {
            _teamMemberService = teamMemberService;
            _logger = logger;
        }

        /// <summary>
        /// 获取分页的团队成员列表
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns>团队成员列表</returns>
        [HttpGet]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        public async Task<ActionResult<PagedResultDto<TeamMemberDto>>> GetPagedList([FromQuery] PagedQueryDto query)
        {
            try
            {
                var result = await _teamMemberService.GetPagedListAsync(query);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting paged team members");
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 根据团队ID获取成员列表
        /// </summary>
        /// <param name="teamId">团队ID</param>
        /// <returns>团队成员列表</returns>
        [HttpGet("team/{teamId:long}")]
        [ProducesResponseType(200)]
        [ProducesResponseType(404)]
        public async Task<ActionResult<List<TeamMemberDto>>> GetByTeamId(long teamId)
        {
            try
            {
                var result = await _teamMemberService.GetByTeamIdAsync(teamId);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting team members for team {TeamId}", teamId);
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 根据用户ID获取团队成员信息
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>团队成员列表</returns>
        [HttpGet("user/{userId:long}")]
        [ProducesResponseType(200)]
        [ProducesResponseType(404)]
        public async Task<ActionResult<List<TeamMemberDto>>> GetByUserId(long userId)
        {
            try
            {
                var result = await _teamMemberService.GetByUserIdAsync(userId);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting team members for user {UserId}", userId);
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 根据ID获取团队成员详情
        /// </summary>
        /// <param name="id">团队成员ID</param>
        /// <returns>团队成员详情</returns>
        [HttpGet("{id:long}")]
        [ProducesResponseType(200)]
        [ProducesResponseType(404)]
        public async Task<ActionResult<TeamMemberDto>> GetById(long id)
        {
            try
            {
                var result = await _teamMemberService.GetByIdAsync(id);
                if (result == null)
                {
                    return NotFound();
                }
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting team member {Id}", id);
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 创建团队成员
        /// </summary>
        /// <param name="dto">团队成员数据</param>
        /// <returns>创建的团队成员</returns>
        [HttpPost]
        [ProducesResponseType(201)]
        [ProducesResponseType(400)]
        public async Task<ActionResult<TeamMemberDto>> Create([FromBody] TeamMemberDto dto)
        {
            try
            {
                var result = await _teamMemberService.CreateAsync(dto);
                return CreatedAtAction(nameof(GetById), new { id = result.TeamId }, result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error creating team member");
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 更新团队成员
        /// </summary>
        /// <param name="id">团队成员ID</param>
        /// <param name="dto">更新的团队成员数据</param>
        /// <returns>更新后的团队成员</returns>
        [HttpPut("{id:long}")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(404)]
        public async Task<ActionResult<TeamMemberDto>> Update(long id, [FromBody] TeamMemberDto dto)
        {
            try
            {
                var result = await _teamMemberService.UpdateAsync(id, dto);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating team member {Id}", id);
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 删除团队成员
        /// </summary>
        /// <param name="id">团队成员ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id:long}")]
        [ProducesResponseType(200)]
        [ProducesResponseType(404)]
        public async Task<ActionResult<bool>> Delete(long id)
        {
            try
            {
                var result = await _teamMemberService.DeleteAsync(id);
                if (!result)
                {
                    return NotFound();
                }
                return Ok(new { success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error deleting team member {Id}", id);
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 批量删除团队成员
        /// </summary>
        /// <param name="ids">团队成员ID列表</param>
        /// <returns>删除结果</returns>
        [HttpPost("batch-delete")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        public async Task<ActionResult<bool>> BatchDelete([FromBody] List<long> ids)
        {
            try
            {
                var result = await _teamMemberService.BatchDeleteAsync(ids);
                return Ok(new { success = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error batch deleting team members");
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 添加用户到团队
        /// </summary>
    /// <param name="teamId">团队ID</param>
    /// <param name="request">请求体，包含要添加的用户ID与角色</param>
        /// <returns>团队成员信息</returns>
        [HttpPost("team/{teamId:long}/add-member")]
        [ProducesResponseType(201)]
        [ProducesResponseType(400)]
        public async Task<ActionResult<TeamMemberDto>> AddMember(
            long teamId, 
            [FromBody] AddTeamMemberRequest request)
        {
            try
            {
                var result = await _teamMemberService.AddMemberAsync(teamId, request.UserId, request.Role);
                return CreatedAtAction(nameof(GetById), new { id = result.TeamId }, result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error adding member to team {TeamId}", teamId);
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 从团队移除用户
        /// </summary>
        /// <param name="teamId">团队ID</param>
        /// <param name="userId">用户ID</param>
        /// <returns>移除结果</returns>
        [HttpDelete("team/{teamId:long}/members/{userId:long}")]
        [ProducesResponseType(200)]
        [ProducesResponseType(404)]
        public async Task<ActionResult<bool>> RemoveMember(long teamId, long userId)
        {
            try
            {
                var result = await _teamMemberService.RemoveMemberAsync(teamId, userId);
                return Ok(new { success = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error removing member from team {TeamId}", teamId);
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 更新团队成员角色
        /// </summary>
        /// <param name="teamId">团队ID</param>
        /// <param name="userId">用户ID</param>
        /// <param name="request">角色更新请求</param>
        /// <returns>更新结果</returns>
        [HttpPut("team/{teamId:long}/members/{userId:long}/role")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        public async Task<ActionResult<bool>> UpdateMemberRole(
            long teamId, 
            long userId, 
            [FromBody] UpdateRoleRequest request)
        {
            try
            {
                var result = await _teamMemberService.UpdateMemberRoleAsync(teamId, userId, request.Role);
                return Ok(new { success = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating member role in team {TeamId}", teamId);
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 检查用户是否为团队成员
        /// </summary>
        /// <param name="teamId">团队ID</param>
        /// <param name="userId">用户ID</param>
        /// <returns>是否为团队成员</returns>
        [HttpGet("team/{teamId:long}/members/{userId:long}/check")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<bool>> IsMember(long teamId, long userId)
        {
            try
            {
                var result = await _teamMemberService.IsMemberAsync(teamId, userId);
                return Ok(new { isMember = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error checking if user is team member");
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 获取用户在团队中的角色
        /// </summary>
        /// <param name="teamId">团队ID</param>
        /// <param name="userId">用户ID</param>
        /// <returns>团队角色</returns>
        [HttpGet("team/{teamId:long}/members/{userId:long}/role")]
        [ProducesResponseType(200)]
        [ProducesResponseType(404)]
        public async Task<ActionResult<string>> GetMemberRole(long teamId, long userId)
        {
            try
            {
                var result = await _teamMemberService.GetMemberRoleAsync(teamId, userId);
                if (result == null)
                {
                    return NotFound();
                }
                return Ok(new { role = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting member role");
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 获取团队的管理员列表
        /// </summary>
        /// <param name="teamId">团队ID</param>
        /// <returns>管理员列表</returns>
        [HttpGet("team/{teamId:long}/admins")]
        [ProducesResponseType(200)]
        public async Task<ActionResult<List<TeamMemberDto>>> GetTeamAdmins(long teamId)
        {
            try
            {
                var result = await _teamMemberService.GetTeamAdminsAsync(teamId);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting team admins for team {TeamId}", teamId);
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 批量导入团队成员
        /// </summary>
        /// <param name="teamId">团队ID</param>
        /// <param name="members">成员数据列表</param>
        /// <returns>导入结果</returns>
        [HttpPost("team/{teamId:long}/import")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        public async Task<ActionResult<List<TeamMemberDto>>> BatchImport(
            long teamId, 
            [FromBody] List<TeamMemberDto> members)
        {
            try
            {
                var result = await _teamMemberService.BatchImportAsync(teamId, members);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error batch importing team members");
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 导出团队成员
        /// </summary>
        /// <param name="teamId">团队ID</param>
        /// <returns>导出文件</returns>
        [HttpGet("team/{teamId:long}/export")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        public async Task<ActionResult> Export(long teamId)
        {
            try
            {
                var data = await _teamMemberService.ExportAsync(teamId);
                return File(data, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", 
                    $"team-members-{teamId}-{DateTime.Now:yyyyMMddHHmmss}.xlsx");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error exporting team members");
                return BadRequest(new { message = ex.Message });
            }
        }
    }

    /// <summary>
    /// 添加团队成员请求
    /// </summary>
    public class AddTeamMemberRequest
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        public long UserId { get; set; }
        
        /// <summary>
        /// 角色
        /// </summary>
        public string Role { get; set; } = "Member";
    }

    /// <summary>
    /// 更新角色请求
    /// </summary>
    public class UpdateRoleRequest
    {
        /// <summary>
        /// 角色
        /// </summary>
        public string Role { get; set; } = string.Empty;
    }
}
